const female = document.querySelector('.female');
const male = document.querySelector('.male');
let globalRankData = null;
let currentGender = 2; // 默认女生
let currentRankType = 9; // 默认畅销榜
let currentGroupLength = 3; 
const RANK_TYPE_MAP = {
    '畅销榜': 9,
    '点击榜': 10,
    '打赏榜': 11,
    '推荐榜': 12,
    '新书榜': 13,
    '更新榜': 14,
    '书评榜': 15,
    '财神榜': 16
};
const array = [
  ['日榜', '月榜', '总榜'],
  ['日榜', '月榜', '总榜'],
  ['日榜', '月榜', '总榜'],
  ['日榜', '月榜', '总榜'],
  [],
  [],
  ['月榜', '总榜'],
  ['月榜', '总榜']
];
// 榜单类型 → array子数组索引 的映射
const RANK_TYPE_TO_ARRAY_INDEX = {
  9: 0,  // 畅销榜 → array[0]
  10: 1, // 点击榜 → array[1]
  11: 2, // 打赏榜 → array[2]
  12: 3, // 推荐榜 → array[3]
  13: 4, // 新书榜 → array[4]
  14: 5, // 更新榜 → array[5]
  15: 6, // 书评榜 → array[6]
  16: 7  // 财神榜 → array[7]
};
// 跳转详情页

function jumps(id){
     if(sessionStorage.getItem('account')){
             window.location.href=`./yy-bookDetail.html?id=${id}`;
        }else{
              window.location.href='./login.html';
        }
    console.log(id)
}

const comment = document.querySelector('.comment');
const fl=document.querySelector('.fl')
// 遍历 array 中的每个子数组
array.forEach((subArray, groupIndex) => {
  // 为每组创建一个容器
  const groupContainer = document.createElement('div');
  groupContainer.className = 'rank-group'; // 每组的类名，可用于加样式

  if (subArray.length === 0) {
    // 子数组为空时，显示“无数据”提示
    const emptyItem = document.createElement('p');
    emptyItem.className = 'empty';
    emptyItem.textContent = '暂无榜单数据';
    groupContainer.appendChild(emptyItem);
  } else {
    // 遍历子数组中的每个榜单名称
    subArray.forEach((rankName, index) => {
      const listItem = document.createElement('li');
      // 每组的第一个标签默认高亮
      listItem.className = index === 0 ? 'actives' : '';
      listItem.textContent = rankName;

      // 点击事件：切换当前组内的高亮状态
      listItem.addEventListener('click', () => {
        // 找到当前组内的所有标签
        const allItemsInGroup = groupContainer.querySelectorAll('li');
        // 移除所有标签的高亮
        allItemsInGroup.forEach(item => item.classList.remove('actives'));
        // 给当前点击的标签添加高亮
        listItem.classList.add('actives');
      });

      groupContainer.appendChild(listItem);
    });
  }

  // 将当前组添加到 comment 容器中
  comment.appendChild(groupContainer);
});
// 页面加载时先获取性别列表
// 页面加载时先获取性别列表
fetch('https://app2.motie.com/ranking/names', {
    headers: { os: 'pc' }
}).then(res => res.json())
  .then(res1 => {
    // 先添加“女生榜单”总分类标签
    female.innerHTML = `<p onclick="getsex(event)" class="gender-main-tab on">女生榜单</p>`;
    // 再添加女生下的子标签
    res1.data.forEach(item => {
        const rankType = RANK_TYPE_MAP[item.desc] || 9;
        female.innerHTML += `
            <p onclick="getapp(event, 2, '${item.desc}')" data-rank-type="${rankType}" class="gender-sub-tab">
                ${item.desc}
            </p>
        `;
    });

    //先添加“男生榜单”总分类标签
    male.innerHTML = `<p onclick="getsex(event)" class="gender-main-tab">男生榜单</p>`;
    // 再添加男生下的子标签
    res1.data.forEach(item => {
        const rankType = RANK_TYPE_MAP[item.desc] || 9;
        male.innerHTML += `
            <p onclick="getapp(event, 1, '${item.desc}')" data-rank-type="${rankType}" class="gender-sub-tab">
                ${item.desc}
            </p>
        `;
    });
    
    // 默认加载女生总分类的榜单数据
    getsex({ target: female.querySelector('.gender-main-tab') });
}).catch(err => {
    console.log('性别列表加载失败:', err);
});

function getsex(event) {
    //  显式处理event，避免兼容性问题
    if (!event || !event.target) {
        console.error('getsex函数缺少有效event参数');
        return;
    }
    const target = event.target;
    const text = target.innerHTML?.trim() || '';

    // 获取区域元素并检查存在性
    const rightbar = document.querySelector('.rightbar');
    const rightlist = document.querySelector('.rightlist');
    const arrayIndex = RANK_TYPE_TO_ARRAY_INDEX[currentRankType];
    const targetSubArray = array[arrayIndex] || [];
    renderCommentTags(targetSubArray);
    if (!rightbar || !rightlist) {
        console.error('未找到rightbar或rightlist元素');
        return;
    }

    document.querySelectorAll('.gender-main-tab').forEach(tab => {
        tab.classList.remove('on');
    });
    target.classList.add('on');

    // 取消所有子标签的高亮
    document.querySelectorAll('.gender-sub-tab').forEach(tab => {
        tab.classList.remove('on');
    });

    //  根据总分类文本切换区域显示，并更新当前性别
    if (text === '女生榜单') {
        currentGender = 2; // 更新为女生性别
       
        activateDefaultSubTab(2, '畅销榜');
        rightbar.style.display = 'block';
        rightlist.style.display = 'none';
        updateRightBar(currentGender); // 加载女生总分类数据
    } else if (text === '男生榜单') {
        currentGender = 1; // 更新为男生性别
    //    （默认子标签）
        activateDefaultSubTab(1, '畅销榜');
        rightbar.style.display = 'block';
        rightlist.style.display = 'none';
        updateRightBar(currentGender); // 加载男生总分类数据
    }

    console.log(`已切换到${text}，当前性别：${currentGender}`);
}

// 新增：激活指定性别下的默认子标签（如“畅销榜”）
function activateDefaultSubTab(sex, defaultTabDesc) {
    //  清空所有子标签的高亮
    document.querySelectorAll('.gender-sub-tab').forEach(tab => {
        tab.classList.remove('on');
    });
    //  找到当前性别下的默认子标签
    const defaultSubTab = document.querySelector(`.${sex === 2 ? 'female' : 'male'} .gender-sub-tab`);
    if (defaultSubTab) {
        // 更新当前榜单类型为默认子标签的类型
        currentRankType = parseInt(defaultSubTab.dataset.rankType) || 9;
        // 为默认子标签名称
        fl.innerHTML = defaultSubTab.textContent;
    }
}


function getapp(event, sex, tabDesc) {
    // 参数容错
    if (!event || !sex || !tabDesc) {
        console.error('getapp函数参数缺失');
        return;
    }
    const target = event.currentTarget;
    fl.innerHTML = tabDesc; //

    document.querySelectorAll('.gender-main-tab').forEach(tab => {
        tab.classList.remove('on');
    });
    // 取消所有子标签的选中状态
    document.querySelectorAll('.gender-sub-tab').forEach(tab => {
        tab.classList.remove('on');
    });
    // 仅给当前点击的子标签添加高亮
    target.classList.add('on');

    // 更新当前状态
    currentGender = sex;
    currentRankType = parseInt(target.dataset.rankType) || 9;

    // 切换到rightlist区域，并加载子标签对应的榜单数据
    const rightbar = document.querySelector('.rightbar');
    const rightlist = document.querySelector('.rightlist');
    const arrayIndex = RANK_TYPE_TO_ARRAY_INDEX[currentRankType];
    const targetSubArray = array[arrayIndex] || [];
    renderCommentTags(targetSubArray);
    if (rightbar && rightlist) {
        rightbar.style.display = 'none';
        rightlist.style.display = 'block';
    }

    //  加载左侧和右侧列表数据
    getlists(currentRankType, currentGender);
    console.log(`当前选中：${tabDesc}（类型：${currentRankType}，性别：${currentGender}）`);
}

function renderCommentTags(subArray) {
  comment.innerHTML = ''; // 清空原有内容
  const groupContainer = document.createElement('div');
  groupContainer.className = 'rank-group';

  if (subArray.length === 0) {
    const emptyItem = document.createElement('p');
    emptyItem.className = 'empty';
    emptyItem.textContent = '暂无榜单数据';
    groupContainer.appendChild(emptyItem);
  } else {
    subArray.forEach((rankName, index) => {
      const listItem = document.createElement('li');
      listItem.className = index === 0 ? 'actives' : '';
      listItem.textContent = rankName;

      listItem.addEventListener('click', () => {
        const allItems = groupContainer.querySelectorAll('li');
        allItems.forEach(item => item.classList.remove('actives'));
        listItem.classList.add('actives');
      });

      groupContainer.appendChild(listItem);
    });
  }

  comment.appendChild(groupContainer);
}
// 更新右侧榜单数据
function updateRightBar(sex) {
    const rightbar = document.querySelector('.rightbar');
    rightbar.innerHTML = '<div class="loading">切换榜单中...</div>';
    
    // 传递性别参数到接口
    fetch(`https://app2.motie.com/ranking/all?siteId=4&sex=${sex}`, {
        headers: { os: 'pc' }
    })
    .then(res => {
        if (!res.ok) throw new Error(`HTTP错误：${res.status}`);
        return res.json();
    })
    .then(res1 => {
        globalRankData = res1;
        rightbar.innerHTML = ''; // 清空原有内容
        renderRankContainers(res1.data);
    })
    .catch(err => {
        console.log('榜单数据加载失败:', err);
        rightbar.innerHTML = `<div class="error">${sex === 1 ? '男生' : '女生'}榜单加载失败</div>`;
    });
}

// 右侧榜单核心逻辑
const rightbar = document.querySelector('.rightbar');

// 页面加载时获取右侧榜单初始数据（女生）
fetch('https://app2.motie.com/ranking/all?siteId=4&sex=2', {
    headers: { os: 'pc' }
}).then(res => res.json())
  .then(res1 => {
    globalRankData = res1;
    renderRankContainers(res1.data);
}).catch(err => {
    console.log('榜单数据加载失败:', err);
    if (rightbar) rightbar.innerHTML = '<div class="error">榜单加载失败</div>';
});

// 渲染榜单容器
function renderRankContainers(data) {
    if (!data || !Array.isArray(data)) return;
    data.forEach((listItem, listIndex) => {
        const allbank = document.createElement('div');
        allbank.className = 'allbank';
        
        let tabsHtml = '';
        const defaultTabIndex = 0;
        if (listItem.item && Array.isArray(listItem.item)) {
            listItem.item.forEach((tabItem, tabIndex) => {
                tabsHtml += `
                    <li class="${tabIndex === defaultTabIndex ? 'on' : ''}" 
                        onmouseover="switchTab(${listIndex}, ${tabIndex}, '${tabItem.title}')">
                        ${tabItem.title}
                    </li>
                `;
            });
        }
        
        allbank.innerHTML = `
            <div class="listtab3">
                <div class="listtile">
                    <div class="mod-title">
                        <div class="title-bd">
                            <h2>${listItem.name || '未知榜单'}</h2>
                        </div>
                    </div>
                </div>
                <ul class="tab-ul">${tabsHtml}</ul>
                <div class="con" data-list-index="${listIndex}">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        `;
        
        if (rightbar) rightbar.appendChild(allbank);
        
        if (listItem.item && listItem.item.length > defaultTabIndex) {
            switchTab(listIndex, defaultTabIndex, listItem.item[defaultTabIndex].title);
        }
    });
}

// 切换标签并渲染内容
function switchTab(listIndex, tabIndex, tabType) {
    const tabs = document.querySelectorAll(`.allbank:nth-child(${listIndex + 1}) .tab-ul li`);
    tabs.forEach(li => li.classList.remove('on'));
    if (tabs[tabIndex]) tabs[tabIndex].classList.add('on');
    
    const conElement = document.querySelector(`.con[data-list-index="${listIndex}"]`);
    if (!conElement) return;
    conElement.innerHTML = '<div class="loading">加载中...</div>';
    
    try {
        if (!globalRankData || !globalRankData.data || !globalRankData.data[listIndex]) {
            throw new Error('全局榜单数据不存在');
        }
        const listData = globalRankData.data[listIndex];
        if (!listData.item || !listData.item[tabIndex]) {
            throw new Error(`未找到索引为${listIndex}-${tabIndex}的榜单数据`);
        }
        const tabData = listData.item[tabIndex];
        const contentData = tabData.content || [];
        
        renderContent(conElement, contentData, tabType, listIndex);
    } catch (err) {
        console.error('渲染内容失败:', err);
        if (conElement) conElement.innerHTML = `<div class="error">${tabType}榜数据加载失败</div>`;
    }
}

// 渲染具体内容
function renderContent(container, data, tabType, listIndex) {
    if (!container) return;
    if (data.length === 0) {
        container.innerHTML = `
            <div class="empty">暂无${tabType}榜数据</div>
            <a href="#" class="more">查看更多>></a>
        `;
        return;
    }
    
    let contentHtml = '<div class="rank-1">';
    
    data.forEach((item, index) => {
        const bookName = item.bookName || '未知书名';
        const authorName = item.authorName || '未知作者';
        const bookIconUrl = item.bookIconUrl || 'https://picsum.photos/80/120';
        // const bookHref = item.bookUrl || '#';
        
        if (index === 0) {
            contentHtml += `
                <div class="top">
                    <span class="num">${index + 1}</span>
                    <div class="book-block">
                        <div class="first">
                            <a href="./yy-bookDetail.html?id=${item.bookId}" target="_blank" rel="noopener">
                                <img src="${bookIconUrl}" alt="${bookName}" loading="lazy">
                            </a>
                        </div>
                        <div class="two">
                            <a href="./yy-bookDetail.html?id=${item.bookId}" target="_blank" rel="noopener">${bookName}</a>
                            <p>作者：<span>${authorName}</span></p>
                        </div>
                    </div>
                </div>
            `;
        } else {
            contentHtml += `
                <div class="top1">
                    <span class="num">${index + 1}</span>
                    <a href="./yy-bookDetail.html?id=${item.bookId}" target="_blank" rel="noopener">${bookName}</a>
                </div>
            `;
        }
    });
    
    contentHtml += `
        </div>
        <a href="#" class="more" onclick="showMore(${listIndex}, '${tabType}')">查看更多>></a>
    `;
    
    container.innerHTML = contentHtml;
}



// 左侧畅销榜
const lists = document.querySelector('.defaultRank');
function getlists(type, sex) {
    if (!lists) return;
    lists.innerHTML = '<div class="loading">加载中...</div>';
    
    // 将类型和性别参数传递到接口
    fetch(`https://app2.motie.com/ranking/detail?group=3&siteId=4&rankType=${type}&sex=${sex}&pageSize=30`, {
    headers: { os: 'pc' }
})
.then(res => {
    if (!res.ok) throw new Error(`请求失败：${res.status}`);
    return res.json();
})
.then(res1 => {
    if (!res1.data || !Array.isArray(res1.data)) {
        lists.innerHTML = '<div class="error">数据加载异常</div>';
        return;
    }
    lists.innerHTML = '';
    res1.data.forEach((items, index) => {
        const time = new Date(items.lastChapterTime);
        const year = time.getFullYear();
        const month = (time.getMonth() + 1).toString().padStart(2, '0');
        const day = time.getDate().toString().padStart(2, '0');
        const hour = time.getHours().toString().padStart(2, '0');
        const minute = time.getMinutes().toString().padStart(2, '0');
        const seconds = time.getSeconds().toString().padStart(2, '0');
        const statText = items.bookPv ? `${items.bookPv} 点击` : `${items.words || 0} 总字数`;
        const statusText = items.finished === true ? '完结' : '连载中';
        
        lists.innerHTML += `
<div class="secd-rank-list">
    <div class="app">
        <div class="imgs"  onclick="jumps(${items.bookId})">
            <img src="${items.bookIconUrl || 'https://picsum.photos/80/120'}" alt="${items.bookName}">
        </div>
        <div class="rightimg">
            <a class="ones" href="./yy-bookDetail.html?id=${items.bookId}">
                <span class="one">${index + 1}</span>
                ${items.bookName || '未知书名'}
            </a>
            <p>
                <span>${items.authorName || '未知作者'}</span> | <span>${items.categoryVO?.name || '未知分类'}</span>| ${statusText} <span class="nums">${statText} </span>
            </p>
            <p class="info">${items.introduce || '暂无简介'}</p>
            <div class="red">
                <a href="${items.lastChapterUrl || '#'}">最近更新 ${items.lastChapterName || '未知章节'}</a>
<span>| ${year}-${month}-${day} ${hour}:${minute}:${seconds}</span>
            </div>
        </div>
    </div>
    <div class="bigbutton">
        <a href="${items.bookUrl || '#'}" class="detailbutton">书籍详情</a>
        <a href="javascript:;" class="add" onclick="addToBookshelf('${items.bookId || ''}', '${items.bookName || ''}')">加入书架</a>
    </div>
</div>
`;
    });
})
.catch(err => {
    console.log('左侧榜单加载失败:', err);
    if (lists) lists.innerHTML = '<div class="error">加载失败</div>';
});
}



// 页面加载完成后初始化左侧畅销榜
document.addEventListener('DOMContentLoaded', () => {
    getlists(currentRankType, currentGender);
});
